import { RouterView } from 'vue-router';

export const OutletComponet = RouterView;

export const defaultRoutes = [
  {
    path: '/:pathMatch(.*)*',
    name: 'not-found',
    component: () => import('@/views/error/404.vue'),
    meta: { title: 'not-found', constant: true }
  }
];

export const commonRoutes = [
  {
    path: '/404',
    name: '404',
    component: () => import('@/views/error/404.vue'),
    meta: { title: '404', constant: true }
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/index.vue'),
    meta: { title: 'login', constant: true }
  },
  {
    path: '/',
    name: 'layout',
    component: () => import('@/layout/index.vue'),
    children: [
      {
        path: '/',
        name: 'index',
        component: () => import('@/views/index.vue'),
        meta: { title: '首页' }
      },
      {
        path: 'file',
        name: 'file',
        component: () => import('@/views/file/index.vue'),
        meta: { title: '文件管理' }
      },
      {
        path: 'result',
        name: 'result',
        redirect: '/',
        meta: { title: '结果反馈' },
        children: [
          {
            path: 'export/:taskId',
            name: 'result-export',
            component: () => import('@/views/result/r-export.vue'),
            meta: { title: '导出状态' }
          }
        ]
      }
    ]
  }
];

const modules = import.meta.glob('@/views/**/*.vue');

export const loadView = (path) => {
  const module = modules[`/src/views${path}.vue`] || modules[`/src/views${path}/index.vue`];
  return module ?? (() => import('@/views/error/r-developing.vue'));
};

export function convertRoutes(routes) {
  return routes?.map(({ path, name, component, children, meta, query }) => {
    const router = { path, name, meta };

    if (component && component.toLocaleLowerCase() === 'outlet') {
      router.component = OutletComponet;
      router.children = convertRoutes(children);
    } else if (component && children && children.length) {
      router.component = OutletComponet;
      router.children = [{ path, component: loadView(component) }];
      router.children.push(...convertRoutes(children));
    } else if (component && !children) {
      router.component = loadView(component, false);
    }

    if (query) {
      router.path += `/:${query.replace(/,/g, '/:')}`;
      router.props = true;
    }

    return router;
  });
}
